

function [gcampmov,baselinegcamp,baselineStdGcamp,normalizationRange] = gcampProcess_v1_0(gcampmov,micronsPerPixel,smoothsize,framesPerStim,prestimframes,totalFrameTime,parenchymaMask)

%% process gcamp data to make it more easily processed:
% heavy spatial smoothing:
if nargin < 3 || isempty(smoothsize)
    smoothsize = 100;        %width of gaussian kernel for smoothing (in microns)
end
if nargin < 7 || isempty(parenchymaMask)
    parenchymaMask = true(size(gcampmov,1),size(gcampmov,2));
end
smoothsize = smoothsize/micronsPerPixel;
h = fspecial('gaussian',round(smoothsize*3),smoothsize);        %generate gaussian kernel for smoothing
% you get some edge artifacts outside the window mask which you'll just have to mask out with the window mask:
SE = strel("disk",ceil(smoothsize/2));
erodedMask = imerode(parenchymaMask,SE);

for n = 1:size(gcampmov,3)
    cur = gcampmov(:,:,n);
    cur(~parenchymaMask) = nan;
    temp = nanconv(cur,h,'edge');
    temp(~erodedMask) = nan;
    gcampmov(:,:,n) = temp;
end



% reshape into stim blocks:
gcampmov = reshape(gcampmov,size(gcampmov,1),size(gcampmov,2),framesPerStim/2,size(gcampmov,3)/framesPerStim*2);

% calculate baseline gcamp across all the stims; since have the image
% registration this should work well:
baselinegcamp = mean(gcampmov(:,:,prestimframes,:),3);
baselinegcamp = mean(baselinegcamp,4);
baselineStdGcamp = zeros(size(baselinegcamp));
for n = 1:size(gcampmov,4)
    baselineStdGcamp = baselineStdGcamp + std(gcampmov(:,:,prestimframes,n),0,3)/size(gcampmov,4);
end

for n = 1:size(gcampmov,3)
    for n2 = 1:size(gcampmov,4)
        gcampmov(:,:,n,n2) = gcampmov(:,:,n,n2)./baselinegcamp;
    end
end

% temporal smoothing; important to do this AFTER baseline correction or
% else stim signal will bleed into baseline
smoothframes = .75;     %in seconds
smoothframes = round(smoothframes/totalFrameTime);
for n = 1:size(gcampmov,4)
    gcampmov(:,:,2:end,n) = movmean(gcampmov(:,:,2:end,n),smoothframes,3);
end

%% normalize:
minprctile = 15;
maxprctile = 99;
gcampmov(gcampmov==0) = nan;
normalizationRange = [prctile(gcampmov(:),minprctile),prctile(gcampmov(:),maxprctile)];

gcampmov = (gcampmov-normalizationRange(1))/(normalizationRange(2)-normalizationRange(1));
gcampmov(gcampmov<0) = 0;



